package com.app.island.cash.utilstools

import android.annotation.SuppressLint
import android.content.Context
import android.location.*
import android.os.Bundle
import com.orhanobut.logger.Logger
import java.util.*

class AddressUtils private constructor() {
    private var mContext: Context? = null
    var longitude = 0.0
    var latitude = 0.0
    var detailAddress = "unknown"
    fun initLocation(context: Context?) {
        mContext = context
        val location = location ?: return
        latitude = location.latitude
        longitude = location.longitude
        detailAddress = getDetailAddress(location)
        Logger.e("latitude:$latitude     longitude:$longitude   detailAddress:$detailAddress")
    }

    private fun getDetailAddress(location: Location?): String {
        var result: List<Address>? = null
        try {
            if (location != null) {
                val gc = Geocoder(mContext, Locale.getDefault())
                result = gc.getFromLocation(
                    location.latitude,
                    location.longitude, 1
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e(e.message!!)
        }
        return if (result == null || result.size == 0) {
            "unKnown"
        } else {
            result[0].getAddressLine(0)
        }
    }//从网络获取经纬度//当GPS信号弱没获取到位置的时候再从网络获取//从gps获取经纬度

    /**
     * 获取地理位置，先根据GPS获取，再根据网络获取
     *
     * @return
     */
    @get:SuppressLint("MissingPermission")
    val location: Location?
        get() {
            var location: Location? = null
            var locationManager: LocationManager? = null
            try {
                if (mContext == null) {
                    return null
                }
                locationManager =
                    mContext!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                if (locationManager == null) {
                    return null
                }
                if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                    if (location == null) { //当GPS信号弱没获取到位置的时候再从网络获取
                        location = locationByNetwork
                    }
                } else {    //从网络获取经纬度
                    location = locationByNetwork
                }
            } catch (e: Exception) {
            }
            return location
        }

    /**
     * 判断是否开启了GPS或网络定位开关
     *
     * @return
     */
    val isLocationProviderEnabled: Boolean
        get() {
            var result = false
            val locationManager =
                mContext!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                    ?: return result
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
                    LocationManager.NETWORK_PROVIDER
                )
            ) {
                result = true
            }
            return result
        }

    /**
     * 获取地理位置，先根据GPS获取，再根据网络获取
     *
     * @return
     */
    @get:SuppressLint("MissingPermission")
    private val locationByNetwork: Location?
        private get() {
            var location: Location? = null
            val locationManager =
                mContext!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            try {
                if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        1000,
                        0f,
                        mLocationListener
                    )
                    location =
                        locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                }
            } catch (e: Exception) {
            }
            return location
        }

    companion object {
        private var mInstance: AddressUtils? = null
        private val mLocationListener: LocationListener = object : LocationListener {
            // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
            override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

            // Provider被enable时触发此函数，比如GPS被打开
            override fun onProviderEnabled(provider: String) {}

            // Provider被disable时触发此函数，比如GPS被关闭
            override fun onProviderDisabled(provider: String) {}

            //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
            override fun onLocationChanged(location: Location) {}
        }
        val instance: AddressUtils?
            get() {
                if (mInstance == null) {
                    mInstance = AddressUtils()
                }
                return mInstance
            }
    }
}